import time
import sys
from os import getcwd
from PyQt4.QtGui import QWidget,QPainter,QPen,QFont,QVBoxLayout,QGridLayout
from PyQt4.QtCore import QUrl,QEvent, QSize,Qt,pyqtSignal
from eventEngine import *
from vgform import VGDataMonitorForm
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *

import webbrowser


class WebVGForm(VGDataMonitorForm):
    def __init__(self,eventEngine, parent=None):
        """Constructor"""
        super(WebVGForm, self).__init__(eventEngine,parent)
        self.verticalLayout = QGridLayout(self)
        self.webview = QWebView(self)
        # QWebPage.Notifications
        self.webview.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        self.webview.settings().setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
        self.webview.settings().setAttribute(QWebSettings.LocalStorageEnabled, True)
        self.webview.settings().setLocalStoragePath("/data")
        # self.webview.setContextMenuPolicy(Qt.NoContextMenu)
        self.webview.settings().setDefaultTextEncoding("utf-8")
        self.webview.setGeometry(1, 1, self.width() - 2, self.height() - 2)
        self.webview.setStyleSheet("QWebView{background-color: rgba(255, 193, 245, 0%); }")
        self.webview.page().networkAccessManager().setCookieJar(None)
        self.webview.page().mainFrame().javaScriptWindowObjectCleared.connect(self.setJavaScriptObject)
        self.webview.page().linkClicked.connect(self.linkClicked)
        # self.webview.page().featurePermissionRequested.connect(self.permissionRequested)

        self.webview.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.url = QUrl.fromLocalFile(getcwd() +"/html/index.html")
        self.webview.load(self.url)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.addWidget(self.webview)

        self.webview.loadFinished.connect(self._load_finished)

    def _load_finished(self):
        frame = self.webview.page().mainFrame()
        self.webview.page().setViewportSize(frame.contentsSize())
        self.resize(frame.contentsSize())
        js_scroll = "window.scrollBy(0, 200);"
        self.webview.page().mainFrame().documentElement().evaluateJavaScript(js_scroll)

    def setJavaScriptObject(self):
        self.webview.page().mainFrame().addToJavaScriptWindowObject("_window_", self)

    def linkClicked(self, url):
        webbrowser.open(url.toString())